package com.xtsoft.platform.base.system.controller;

import com.fasterxml.jackson.databind.JsonMappingException;
import com.xtsoft.core.controller.GenericController;
import com.xtsoft.core.repository.QueryFilter;
import com.xtsoft.core.repository.QueryResult;
import com.xtsoft.core.utils.ResultMsg;
import com.xtsoft.core.utils.StringUtils;
import com.xtsoft.platform.base.system.domain.SysRole;
import com.xtsoft.platform.base.system.domain.SysUser;
import com.xtsoft.platform.base.system.service.SysOrganizeService;
import com.xtsoft.platform.base.system.service.SysRoleService;
import com.xtsoft.platform.globe.utils.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.json.JsonParseException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URISyntaxException;
import java.text.ParseException;

/**
 * @ClassName: SysRole
 * @Author author
 * @Vesion 1.0 Create Time:
 *         <p>
 *         <b>Class Description:</b>[TODO]
 *         <p>
 *         REST controller for managing sysRole.
 */

@Tag(name = "系统角色--处理接口")
@RestController

public class SysRoleController extends GenericController {

	private final Logger log = LoggerFactory.getLogger(SysRoleController.class);

	@Autowired
	private SysRoleService sysRoleService;

	@Autowired
	private SysOrganizeService sysOrganizeService;

	/**
	 * <p>
	 * 新增一个角色
	 * </p>
	 * 
	 * @param sysRole 要新增的角色
	 * @return ResponseEntity<ResultMsg>, ResultMsg的Data中包含 角色
	 * @throws URISyntaxException 如果URI语法不正确，则抛URI语法异常
	 * @author Codegen-代码生成器
	 * @date 2020-05-29 13:12:51
	 */
	@Parameter(name = "sysRole", description = "要新增的角色", required = false)
	@Operation(summary  = "新增，根据前台传递的角色新增")
	@PostMapping("/sysRole/add")
	public ResponseEntity<ResultMsg> add(@RequestBody SysRole sysRole)
			throws URISyntaxException {
		if (null == sysRole) {
			return new ResponseEntity<>(new ResultMsg(false, "新增失败，传递的角色为空"), HttpStatus.OK);
		}
		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("新增角色开始......", user.getLoginId(), user.getUsername(),
				getClientIp());
		if (!StringUtils.isEmpty(sysRole.getRoleId())) {
			log.info("新增角色失败，新角色不能具有roleId属性值", user.getLoginId(), user.getUsername(), getClientIp());
			return new ResponseEntity<>(new ResultMsg(false, "新增角色失败，新角色不能具有roleId属性值"), HttpStatus.OK);
		}

		SysRole result = sysRoleService.save(sysRole);
		log.info("新增角色成功", user.getLoginId(), user.getUsername(), getClientIp());
		return new ResponseEntity<ResultMsg>(new ResultMsg(true, "新增成功", result), HttpStatus.OK);
	}


	/**
     * <p>更新一个角色</p>    
     * @param sysRole 要更新的角色
     * @return ResponseEntity<ResultMsg>, json格式
     * @throws URISyntaxException 如果URI语法不正确，则抛URI语法异常
	 * @author Codegen-代码生成器
	 * @date 2020-05-31 23:03:04
     */
			
	@Parameter(name = "sysRole", description = "要更新的角色", required = false)
	@Operation(summary ="更新，根据传递的 角色更新实体")
    @PostMapping("/sysRole/update")

    public ResponseEntity<ResultMsg> update(@RequestBody SysRole sysRole) throws URISyntaxException {
		if(null == sysRole){
			return new ResponseEntity<ResultMsg>(new ResultMsg(false,"更新角色失败，传递的角色为空"),HttpStatus.OK); 
		}
		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("单条更新角色开始......",user.getLoginId(),user.getUsername());
		//若 角色无主键值，说明调用错误
        if (StringUtils.isBlank(sysRole.getRoleId())) {
			log.info("单条更新角色失败，角色对象SchedulerTaskId无属性值",user.getLoginId(),user.getUsername());
			return new ResponseEntity<ResultMsg>(new ResultMsg(false,"更新失败，角色对象RoleId无属性值"),HttpStatus.OK);
        }
  
        SysRole result = sysRoleService.save(sysRole);
		log.info("单条更新角色成功",user.getLoginId(),user.getUsername());
        return new ResponseEntity<ResultMsg>(new ResultMsg(true,"更新成功",result),HttpStatus.OK);
    }	

	/**
	 * <p>
	 * 查询角色列表
	 * </p>
	 * @return ResponseEntity<QueryResult<SchedulerTask>>，json格式
	 * @throws URISyntaxException 如果出错，则产生页码信息的 HTTP headers
	 * @author Codegen-代码生成器
	 * @date 2020-05-31 23:22:05
	 */
	@Operation(summary  = "查询，根据传递的条件查询角色列表，条件参数在Request中")
	@GetMapping("/sysRole/getAll")

	public ResponseEntity<ResultMsg> getAll()
			throws URISyntaxException, JsonParseException, JsonMappingException, IOException, ParseException {

		QueryFilter<SysRole> filter = new QueryFilter<SysRole>(SysRole.class);
		filter.addFilterFromRequest(request);
		QueryResult<SysRole> result = sysRoleService.anyQuery(filter);
		if (null == result || null == result.getResultList() || result.getResultList().size() < 0) {

			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "获取角色列表失败"), HttpStatus.OK);
		}

		return new ResponseEntity<ResultMsg>(new ResultMsg(true, "获取列表成功", result.getResultList()), HttpStatus.OK);
	}

	/**
	 * <p>
	 * 根据角色唯一ID值获取角色
	 * </p>
	 * 
	 * @param id 角色唯一ID值
	 * @return ResponseEntity<SchedulerTask>
	 * @author Codegen-代码生成器
	 * @date 2020-05-31 23:22:05
	 */
	@Parameter(name = "id", description = "对象唯一Id", required = false)
	@Operation(summary  = "获取单个角色，若根据角色唯一Id获取到了多个对象则发生异常")
	@GetMapping("/sysRole/get/{id}")
	
	public ResponseEntity<ResultMsg> get(
			 @PathVariable String id) {
		if (StringUtils.isBlank(id)) {
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "获取单个角色失败，未给定角色的唯一标识"), HttpStatus.OK);
		}
		SysRole sysRole = sysRoleService.get(id);
		/*
		 * <p> ofNullable执行逻辑：如果对象为空，则执行orElse，否则执行.map... return
		 * Optional.ofNullable(sysRole).map(result -> new ResponseEntity<>(result,
		 * HttpStatus.OK)) .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
		 */

		if (null == sysRole) {
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "获取单个角色失败，给定的角色可能被删除"), HttpStatus.OK);
		}
		return new ResponseEntity<ResultMsg>(new ResultMsg(true, "获取成功", sysRole), HttpStatus.OK);
	}

	/**
	 * <p>
	 * 根据调度任务唯一ID值删除单个调度任务
	 * </p>
	 * 
	 * @param id 调度任务唯一ID值
	 * @return ResponseEntity,json格式
	 * @author Codegen-代码生成器
	 * @date 2020-05-31 23:22:05
	 */
	@Parameter(name = "id", description = "角色唯一Id", required = false)
	@Operation(summary  = "删除单个角色")
	@GetMapping("/sysRole/delete/{id}")

	public ResponseEntity<ResultMsg> delete(
			 @PathVariable String id) {
		if (StringUtils.isBlank(id)) {
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "删除单个角色失败，未给定角色的唯一标识"), HttpStatus.OK);
		}
		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("删除单条角色开始",user.getLoginId(),user.getUsername());
		sysRoleService.deleteByRoleId(id);
		log.info("删除单条角色成功",user.getLoginId(),user.getUsername());
		return new ResponseEntity<ResultMsg>(new ResultMsg(true, "删除成功"), HttpStatus.OK);
	}

	/**
	 * 
	 * <b>Description:构建角色树，用于用户授权，授权时需要将用户拥有的权限进行勾选</b><br>
	 * 
	 * @return
	 * @throws ParseException
	 * @Note <b>Author:lgw</b> <br>
	 *       <b>Date:</b>2017年5月4日 下午5:06:32 <br>
	 *       <b>Version:</b> 1.0
	 */
	
	@Parameter(name = "userId", description = "用户Id", required = false)
	@Operation(summary  = "构建角色树，用于用户授权，授权时需要将用户拥有的权限进行勾选")
	@GetMapping("/sysRole/getRoleTree")
	public ResponseEntity<String> getRoleTree(@RequestParam("userId") String userId) throws ParseException {
		log.debug("REST request 查询： SysRole", userId);
		return new ResponseEntity<>(sysRoleService.getRoleTree(userId), HttpStatus.OK);
	}

	/**
	 * Description:角色授权资源
	 * 
	 * @param roleId      角色id
	 * @param ids         资源树id数组
	 * @return
	 */
	
	@Parameter(name = "roleId", description = "角色Id", required = false)
	@Operation(summary  = "角色授权资源")
	@PostMapping("/sysRole/impower")
	public ResponseEntity<String> impower(@RequestParam("roleId") String roleId,
			@RequestParam("resourceId") String resourceId, @RequestParam("ids") String ids) {
		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		String result = sysRoleService.impower(roleId, resourceId, ids);
		log.info("成功给一个角色授权", user.getLoginId(), user.getUsername(), getClientIp());
		return new ResponseEntity<>(result, HttpStatus.OK);
	}
	
	/**
	 * 
	 * <p> 配置仪表盘  </p>  
	 * @param ids dashboard ID集合
	 * @param roleId 角色ID
	 * @return
	 * @return ResponseEntity<ResultMessage>
	 * @throws  
	 * @author litao
	 * @date 2021年9月27日 
	 * @time 上午10:25:55
	 */
	
	@Parameter(name = "ids", description = "id集合", required = false)
	@Operation(summary  = "配置仪表盘")
    @GetMapping("/sysRole/configDashBoard")

    public ResponseEntity<ResultMsg> getDashBoard(@RequestParam("ids") String ids,@RequestParam("pkId") String roleId) {
    	ResultMsg resultMessage=sysRoleService.configDashBoard(ids, roleId);
    	log.info("给角色分配了dashboard");
        return new ResponseEntity<>(resultMessage, HttpStatus.OK);
    }
}
